import React from 'react';
import axios from 'axios';
import * as Cesium from "cesium";
import CryptoJS from "crypto-js";

/** 公共存储,所有公共存储，功能方法类 */
const store = {}
store.name = "test-store-看到此输出表示store正常";//需要使用get,set并且结合本地存储保存到缓存里,让刷新的时候继续有效
store.components = [];
store.forms = [];
store.blocks = [];
store.default =
{
    pageSize: 10 //默认一页显示数量
};
store.saveLoacl = function (name, value) {
    window.localStorage.setItem(name, value);
}
store.clearLocal = function (name) {
    window.localStorage.removeItem(name);
}
store.getLocal = function (name) {
    return window.localStorage.getItem(name);
}
store.addForm = function (name, type, component) {//保存控件状态
    // console.log("new cl");
    // console.log(component)
    // console.log(store.forms)
    try {
        let findi = -1;
        for (var i = 0; i < store.forms.length; i++) {
            if (store.forms[i].name == name && component.props.root != null && store.forms[i].rootKey == component.props.root.props.blockKey) {
                findi = i;
                break;
            }
        }
        if (findi == -1) {
            store.forms[store.forms.length] = { name: name, type: type, component: component, rootKey: component.props.root.props.blockKey };
        } else {
            //store.components[findi].component=component;
        }
    } catch (error) {
        console.log("添加控件出现异常：" + error);
    }
}
store.deleteForm = function (name, rootKey) {
    console.log("释放com");
    console.log(rootKey);

    try {
        let findi = -1;
        for (var i = 0; i < store.forms.length; i++) {
            if (store.forms[i].name == name && store.forms[i].rootKey == rootKey) {
                findi = i;
                break;
            }
        }
        if (findi != -1) {
            store.forms.splice(findi, 1);
        }
    } catch (error) {
        console.log(error);
    }
}
store.checkFormValues = function (rootKey, values) {
    if (values == undefined) return true;
    let allFlag = true;
    for (var i = 0; i < store.forms.length; i++) {
        let find = false;
        for (var j = 0; j < values.length; j++) {
            if (store.forms[i].name == values[j] && this.forms[i].component.props.root.props.blockKey == rootKey) {
                // console.log(values[j]);
                find = true; break;
            }
        }
        if (find == true) {
            let flag = store.forms[i].component.checkVaild();
            if (flag == false) allFlag = false;
        }
    }
    return allFlag;
}
store.getFormValues = function (rootKey, values, pageClear) {
    let post = {};
    console.log("遍历form");
    console.log(store.forms);
    for (var i = 0; i < store.forms.length; i++) {
        let find = false;
        if (values == undefined) find = true;
        else {
            for (var j = 0; j < values.length; j++) {
                if (store.forms[i].name == values[j]) {
                    find = true; break;
                }
            }
        }
        if (find == false) continue;
        if (store.forms[i].type == "Input" || store.forms[i].type == "JsonEditor") {
            if (store.forms[i].component.state.value != undefined && store.forms[i].component.state.value != null
                && this.forms[i].component.props.root.props.blockKey == rootKey) {
                post[store.forms[i].name] = store.forms[i].component.state.value;
            }
        }
        if (store.forms[i].type == "Select") {
            if (store.forms[i].component.state.value != undefined && store.forms[i].component.state.value != null
                && this.forms[i].component.props.root.props.blockKey == rootKey)
                post[store.forms[i].name] = store.forms[i].component.state.value;
        }
        if (store.forms[i].type == "Pager") {
            if (pageClear != undefined)//清除pager
            {
                console.log("clear pager");
                post["page"] = store.forms[i].component.state.page;
                post["pageSize"] = store.forms[i].component.state.pageSize;
                for (var p = 0; p < pageClear.length; p++) {
                    if (pageClear[p] == store.forms[i].name) {
                        store.forms[i].component.setState(
                            {
                                page: 1
                            }
                        );
                        post["page"] = 1;
                        post["pageSize"] = store.forms[i].component.state.pageSize;
                    }
                }
            }
            else if (store.forms[i].component.state.page != undefined && store.forms[i].component.state.page != null
                && this.forms[i].component.props.root.props.blockKey == rootKey) {
                post["page"] = store.forms[i].component.state.page;
                post["pageSize"] = store.forms[i].component.state.pageSize;
            }
        }
        if (store.forms[i].type == "Data") {
            if (store.forms[i].component.state.value != undefined && store.forms[i].component.state.value != null
                && this.forms[i].component.props.root.props.blockKey == rootKey)
                post[store.forms[i].name] = store.forms[i].component.state.value;
        }
    }
    return post;
}
store.addBlock = function (name, component) {//保存控件状态
    try {
        let findi = -1;
        for (var i = 0; i < store.blocks.length; i++) {
            if (store.blocks[i].name == name) {
                findi = i;
                break;
            }
        }
        if (findi == -1 && name != undefined) {
            store.blocks[store.blocks.length] = { name: name, component: component };
        }
    } catch (error) {
        console.log(error);
    }
}
store.deleteBlock = function (name) {
    try {
        let findi = -1;
        for (var i = 0; i < store.blocks.length; i++) {
            if (store.blocks[i].name == name) {
                findi = i;
                break;
            }
        }
        if (findi != -1) {
            store.blocks.splice(findi, 1);
        }
    } catch (error) {
        console.log(error);
    }
}
store.getBlock = (target, func) => {
    try {
        let findi = -1;
        for (var i = 0; i < store.blocks.length; i++) {
            if (store.blocks[i].name == target) {
                findi = i;
                break;
            }
        }

        if (findi == -1) {
            func(null);
        } else {
            func(store.blocks[findi].component);
        }
    } catch (error) {
        console.log(error);
    }
}
store.addComponent = function (name, component) {//保存控件状态
    try {
        let findi = -1;
        for (var i = 0; i < store.components.length; i++) {
            if (store.components[i].name == name) {
                findi = i;
                break;
            }
        }
        if (findi == -1) {
            store.components[store.components.length] = { name: name, component: component };
        } else {
            //store.components[findi].component=component;
        }
    } catch (error) {
        console.log(error);
    }
}
store.deleteComponent = function (name) {
    try {
        let findi = -1;
        for (var i = 0; i < store.components.length; i++) {
            if (store.components[i].name == name) {
                findi = i;
                break;
            }
        }
        if (findi != -1) {
            store.components.splice(findi, 1);
        }
    } catch (error) {
        console.log(error);
    }
}
store.getComponent = (target, func) => {
    try {
        let findi = -1;
        for (var i = 0; i < store.components.length; i++) {
            if (store.components[i].name == target) {
                findi = i;
                break;
            }
        }

        if (findi == -1) {
            func(null);
        } else {
            func(store.components[findi].component);
        }
    } catch (error) {
        console.log(error);
    }
}
store.createComponent = (importComponent) => {
    class AsyncComponent extends React.Component {
        constructor() {
            super();
            this.state = {
                component: null
            }
        }
        async componentDidMount() {
            const { default: component } = await importComponent();
            this.setState({ component: component })
        }
        render() {
            const C = this.state.component;
            return C ? <C {...this.props} /> : null;
        }
    }
    return <AsyncComponent />;
}
store.$http = axios.create({
    // baseURL是在proxyTable中会转发的配置，通过环境变量的判断，可以在开发和生产环境使用不同的url进行请求
    baseURL: 'http://120.55.67.182:8882/api',
    timeout: 15000
});
store.$http.interceptors.request.use(function (config) {
    const token = store.getLocal("access-token");
    //加载在header上
    if (!config.headers) { config.headers = {} }
    config.headers['access-token'] = token
    //加载在传输的数据上
    //if (config.method === 'post') {
    // let data = qs.parse(config.data)
    // config.data = qs.stringify({
    //     ...data,
    //     token: token
    // })
    //} 
    // else if (config.method === 'get') {
    //     config.params = {
    //         ...config.params,
    //         token: token
    //     }
    // }
    return config;
},
    function (error) {
        if (!error.response) {
            return Promise.reject({
                msg: '网络连接超时',
                error
            });
        };
        let msg = '';
        const status = error.response.status;

        switch (status) {
            case 400:
                msg = '错误的请求参数';
                break;
            case 401:
                msg = '没有该操作权限';
                break;
            case 403:
                msg = '请登录';
                break;
            case 404:
                msg = '错误的请求地址';
                break;
            case 500:
            case 501:
            case 502:
            case 503:
            case 504:
                msg = '服务器错误';
                break;
            default:
                msg = '未知错误' + status;
        }
        return Promise.reject({
            msg,
            error
        });
    })
store.$http.interceptors.response.use(function (res) {
    // if (res.status == 200 && res.data.code == -2) {//没有登陆
    //     console.log("no login");
    //     console.log(res);
    // }
    return res.data
})
store.formatDate = (ns) => {
    var date = new Date();
    var nowspan = date.getTime();
    //console.log(nowspan);
    date.setTime(parseInt(ns));
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    return (
        year +
        "-" +
        month +
        "-" +
        day +
        "  " +
        date.getHours() +
        "點" +
        date.getMinutes() +
        "分"
    );
}
store.getPrefContext = (res) => {
    let prefs = "data.rows";
    if (res == undefined) return;
    const pref = prefs.split(".");
    if (pref.length > 3) {
        console.error("表达式不支持");
        return;
    }
    return pref.length == 3 ? res[pref[0]][pref[1]][pref[2]]
        : pref.length == 2 ? res[pref[0]][pref[1]] : res[pref[0]];
}
store.createTdtImageryProvider = (params) => {
    var _0x6b52 = ['157076dLcLMj', '272775PKYdjp', 'subdomains', '&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles', 'appKey', '425308BeGjdF', '245914zPQUmm', 'layer', 'tileMatrixSetID', 'http://t{s}.tianditu.com/', '1198081SircKr', '1EGzAgg', '&tileMatrixSet=', '1061308UpbkrI', '&tk=', '3sKNTwl', 'default', 'WebMapTileServiceImageryProvider', '/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=', 'substr', 'host', 'length', 'url', '431439rTlajA', 'maximumLevel', '1stoZAv', 'minimumLevel', 'style']; (function (_0x193e36, _0x4d736e) { function _0x52c4c8(_0x46b6bd, _0x50da04) { return _0x5173(_0x50da04 - -0x7f, _0x46b6bd); } while (!![]) { try { var _0x4c0b41 = parseInt(_0x52c4c8(0x4, 0xf)) + -parseInt(_0x52c4c8(0x8, 0xa)) + -parseInt(_0x52c4c8(0x9, 0xb)) + -parseInt(_0x52c4c8(0x16, 0x19)) * parseInt(_0x52c4c8(-0x1, 0x5)) + parseInt(_0x52c4c8(0x7, 0x15)) * -parseInt(_0x52c4c8(0x15, 0x10)) + -parseInt(_0x52c4c8(0xf, 0x17)) * -parseInt(_0x52c4c8(0xb, 0x7)) + parseInt(_0x52c4c8(0xa, 0x14)); if (_0x4c0b41 === _0x4d736e) break; else _0x193e36['push'](_0x193e36['shift']()); } catch (_0x329329) { _0x193e36['push'](_0x193e36['shift']()); } } }(_0x6b52, 0xae777)); var tileMatrixSet = 'w', host = params[_0x56d639(-0x50, -0x4d)] || _0x56d639(-0x33, -0x3c), subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']; host[host[_0x56d639(-0x54, -0x4c)] - 0x1] == '/' && (host = host[_0x56d639(-0x56, -0x4e)](0x0, host[_0x56d639(-0x53, -0x4c)] - 0x1)); function _0x56d639(_0x5667a3, _0x56d85b) { return _0x5173(_0x56d85b - -0xce, _0x5667a3); } var url = host + '/' + params[_0x56d639(-0x49, -0x3e)] + '_' + tileMatrixSet + _0x56d639(-0x58, -0x4f) + params[_0x56d639(-0x34, -0x3e)] + _0x56d639(-0x3b, -0x39) + tileMatrixSet + _0x56d639(-0x37, -0x42); url += _0x56d639(-0x43, -0x37) + params[_0x56d639(-0x42, -0x41)]; function _0x5173(_0x21c295, _0x53e80b) { return _0x5173 = function (_0x6b526d, _0x5173b5) { _0x6b526d = _0x6b526d - 0x7d; var _0x45728d = _0x6b52[_0x6b526d]; return _0x45728d; }, _0x5173(_0x21c295, _0x53e80b); } var _0x3166f0 = {}; _0x3166f0[_0x56d639(-0x47, -0x4b)] = url, _0x3166f0[_0x56d639(-0x3e, -0x3e)] = params[_0x56d639(-0x32, -0x3e)], _0x3166f0[_0x56d639(-0x45, -0x46)] = _0x56d639(-0x43, -0x51), _0x3166f0[_0x56d639(-0x3e, -0x43)] = subdomains, _0x3166f0[_0x56d639(-0x40, -0x3d)] = tileMatrixSet, _0x3166f0[_0x56d639(-0x4b, -0x49)] = params[_0x56d639(-0x44, -0x49)] || 0x12, _0x3166f0[_0x56d639(-0x42, -0x47)] = params[_0x56d639(-0x50, -0x47)]; let provider = new Cesium[(_0x56d639(-0x55, -0x50))](_0x3166f0); return provider;
}
store.createGovImageryProvider = (params) => {
    const _0x1981 = ['getHours', 'JWT', 'WebMapTileServiceImageryProvider', '103mhEhGb', 'HmacSHA256', 'log', 'EPSG:4326', 'stringify', 'Base64', '1366044uPXqCa', 'BCDSGS_ff85da5929d640977e18e704795ab7f4', 'HS256', '1775037YLlWLR', '153981JPiciT', 'default', 'enc', 'BCDSGA_b3eb67db313179f6baa31fa9eabad28a', '1668119Ckdwcq', 'Utf8', 'layer', 'user', 'GeographicTilingScheme', '14918uVCbDF', '220652HjyYDv', '1fwsMNs', '7PNnrft', '1OGfxXn', '?jwt=', 'typ', '1839391fYqbak', 'parse', 'replace', 'image/png', 'url', '1SODOIB', 'setHours', 'alg', '&x-bg-auth-type=jwt_auth']; (function (_0x16d66f, _0x73d1f) { function _0x4f52d8(_0x2de006, _0x4e058f) { return _0x2545(_0x2de006 - 0xe2, _0x4e058f); } while (!![]) { try { const _0x2a4ff1 = parseInt(_0x4f52d8(0x1d3, 0x1ce)) + -parseInt(_0x4f52d8(0x1e0, 0x1da)) * parseInt(_0x4f52d8(0x1de, 0x1dc)) + -parseInt(_0x4f52d8(0x1dd, 0x1cc)) * parseInt(_0x4f52d8(0x1f0, 0x1e8)) + -parseInt(_0x4f52d8(0x1d4, 0x1c6)) * -parseInt(_0x4f52d8(0x1e9, 0x1dc)) + -parseInt(_0x4f52d8(0x1d0, 0x1c4)) + -parseInt(_0x4f52d8(0x1e4, 0x1dd)) * -parseInt(_0x4f52d8(0x1df, 0x1d4)) + -parseInt(_0x4f52d8(0x1e1, 0x1d8)) * -parseInt(_0x4f52d8(0x1d8, 0x1e1)); if (_0x2a4ff1 === _0x73d1f) break; else _0x16d66f['push'](_0x16d66f['shift']()); } catch (_0x40d4a0) { _0x16d66f['push'](_0x16d66f['shift']()); } } }(_0x1981, 0xf18b6)); let accessKey = _0x10a223(0x251, 0x249), secretKey = _0x10a223(0x24b, 0x24d), payload = JSON[_0x10a223(0x26e, 0x262)]({ 'key': accessKey, 'exp': new Date()[_0x10a223(0x264, 0x267)](new Date()[_0x10a223(0x267, 0x25d)]() + 0x1) }); function base64UrlEncode(_0x191c71) { var _0x294d92 = CryptoJS[_0x377089(0x18f, 0x1a1)][_0x377089(0x1b0, 0x1c0)][_0x377089(0x1c4, 0x1bf)](_0x191c71), _0x201013 = new RegExp('/', 'g'); function _0x377089(_0x4dd5c5, _0x52fcaa) { return _0x10a223(_0x52fcaa - -0xaf, _0x4dd5c5); } return _0x294d92 = _0x294d92[_0x377089(0x1b7, 0x1b1)](/=+$/, '')[_0x377089(0x1a2, 0x1b1)](/\+/g, '-')[_0x377089(0x1ae, 0x1b1)](_0x201013, '_'), _0x294d92; } const _0x5778db = {}; function _0x10a223(_0x120bc8, _0x438e50) { return _0x2545(_0x120bc8 - 0x15c, _0x438e50); } _0x5778db[_0x10a223(0x265, 0x26b)] = _0x10a223(0x24c, 0x245), _0x5778db[_0x10a223(0x25d, 0x26a)] = _0x10a223(0x268, 0x269); let header = JSON[_0x10a223(0x26e, 0x27b)](_0x5778db), secretSalt = _0x10a223(0x255, 0x24e), before_sign = base64UrlEncode(CryptoJS[_0x10a223(0x250, 0x255)][_0x10a223(0x253, 0x24b)][_0x10a223(0x25f, 0x255)](header)) + '.' + base64UrlEncode(CryptoJS[_0x10a223(0x250, 0x246)][_0x10a223(0x253, 0x255)][_0x10a223(0x25f, 0x26f)](payload)), signature = CryptoJS[_0x10a223(0x26b, 0x272)](before_sign, secretKey); signature = base64UrlEncode(signature); let final_sign = before_sign + '.' + signature; console[_0x10a223(0x26c, 0x277)](final_sign); function _0x2545(_0x1ab4e2, _0x14bad9) { return _0x2545 = function (_0x198118, _0x2545b2) { _0x198118 = _0x198118 - 0xee; let _0x3947f4 = _0x1981[_0x198118]; return _0x3947f4; }, _0x2545(_0x1ab4e2, _0x14bad9); } const baseUrl = params[_0x10a223(0x262, 0x254)] + _0x10a223(0x25c, 0x262) + final_sign + _0x10a223(0x266, 0x263); let provider = new Cesium[(_0x10a223(0x269, 0x26a))]({ 'url': baseUrl, 'layer': params[_0x10a223(0x254, 0x246)], 'style': _0x10a223(0x24f, 0x261), 'format': _0x10a223(0x261, 0x26e), 'tileMatrixSetID': _0x10a223(0x26d, 0x273), 'tileMatrixLabels': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'], 'tilingScheme': new Cesium[(_0x10a223(0x256, 0x254))]() }); return provider;
}
export default store;